# coding=utf-8

from application import app, redis
from common.libs.JsonLibs import bytes_to_obj
from app.model.mysql.gift_type import GiftType as GiftTypeMysql
from app.model.redis.gift_type import GiftType as GiftTypeRedis
from app.json.mysql.gift_type import GiftType as GiftTypeJson


def get_one(gift_type_id):
    redis_gift_type_one = redis.get(GiftTypeRedis.gift_type_one.key % gift_type_id)
    if redis_gift_type_one:
        mysql_gift_type_one = None
    else :
        mysql_gift_type_one = GiftTypeMysql.query.filter(GiftTypeMysql.id == gift_type_id, GiftTypeMysql.is_delete == 0).first()

    if mysql_gift_type_one:
        setInRedis(mysql_gift_type_one)
        gift_json = GiftTypeJson(mysql_gift_type_one).getJson()
    else :
        gift_json = bytes_to_obj(redis_gift_type_one)
    return gift_json


def get_list():
    redis_gift_type_set = redis.smembers(GiftTypeRedis.gift_type_set.key)
    redis_gift_type_list = list(redis_gift_type_set)
    redis_gift_type_list = redis_gift_type_list if redis_gift_type_list else []
    result_list = []
    if not redis_gift_type_list:
        mysql_gift_type_list = GiftTypeMysql.query.filter(GiftTypeMysql.is_delete == 0).all()
        for mysql_gift_type_one in mysql_gift_type_list:
            setInRedis(mysql_gift_type_one)
            gift_type_one_json = GiftTypeJson(mysql_gift_type_one).getJson()
            result_list.append(gift_type_one_json)
        return result_list
    else:
        for gift_type_id in redis_gift_type_list:
            gift_type_one_json = get_one(gift_type_id.decode("utf-8"))
            result_list.append(gift_type_one_json)
        return result_list


def setInRedis(mysql_gift_type_one):
    redis.sadd(GiftTypeRedis.gift_type_set.key, mysql_gift_type_one.id)
    redis.set(GiftTypeRedis.gift_type_one.key % mysql_gift_type_one.id, GiftTypeJson(mysql_gift_type_one).getJsonToRedis())